#!/bin/bash

# read -p "Type the etcd no (like: 0) : "  ETCD_NO
# ETCD_NO=etcd${ETCD_NO}
# PROXY=192.168.0.109:10809
mkdir -p ~/etcd
ETCD_VERSION=v3.6.0-alpha.0
curl --proxy $PROXY -L -o ~/etcd/etcd-$ETCD_VERSION-linux-amd64.tar.gz https://github.com/etcd-io/etcd/releases/download/$ETCD_VERSION/etcd-$ETCD_VERSION-linux-amd64.tar.gz

ssh vagrant@$MASTER02 "mkdir -p ~/etcd"
ssh vagrant@$MASTER03 "mkdir -p ~/etcd"
scp ~/etcd/* vagrant@$MASTER02:~/etcd
scp ~/etcd/* vagrant@$MASTER03:~/etcd

ETCD_NO=etcd2
PKI_PATH=/etc/kubernetes/pki
ETCD_VERSION=v3.6.0-alpha.0

sudo tar xzf ~/etcd/etcd-$ETCD_VERSION-linux-amd64.tar.gz --strip-components=1 -C /usr/local/bin etcd-$ETCD_VERSION-linux-amd64/etcd{,ctl}
# etcd --ETCD_VERSION

sudo chattr -i /etc/resolv.conf
sudo cat <<EOF | sudo tee /etc/resolv.conf
nameserver 192.168.56.11
EOF
# 设置只读
sudo chattr +i /etc/resolv.conf

# best effort, highest priority(ionice设置进程的I/O优先级)
sudo ionice -c2 -n0 -p2 `pgrep etcd`

# 下面配置请查阅https://etcd.io/docs/v3.6/op-guide/configuration/
cat <<EOF | sudo tee /usr/lib/systemd/system/etcd.service
[Unit]
Description=etcd
Documentation=https://github.com/coreos

[Service]
ExecStart=/usr/local/bin/etcd \\
  --name ${ETCD_NO} \\
  --discovery-srv etcd.com \\
  --data-dir /var/lib/etcd \\
  --heartbeat-interval 100 \\
  --election-timeout 1000 \\
  --snapshot-count 5000 \\
  --initial-advertise-peer-urls https://${ETCD_NO}.etcd.com:2380 \\
  --initial-cluster-token etcd-cluster \\
  --initial-cluster-state new \\
  --advertise-client-urls https://${ETCD_NO}.etcd.com:2379 \\
  --listen-client-urls https://0.0.0.0:2379 \\
  --listen-peer-urls https://0.0.0.0:2380 \\
  --client-cert-auth \\
  --trusted-ca-file=${PKI_PATH}/ca.crt \\
  --cert-file=${PKI_PATH}/etcd.crt \\
  --key-file=${PKI_PATH}/etcd.key \\
  --peer-client-cert-auth \\
  --peer-trusted-ca-file=${PKI_PATH}/ca.crt \\
  --peer-cert-file=${PKI_PATH}/etcd.crt \\
  --peer-key-file=${PKI_PATH}/etcd.key
  
Restart=on-failure
RestartSec=5

[Install]
WantedBy=multi-user.target
EOF

sudo systemctl daemon-reload
sudo systemctl enable etcd
sudo systemctl start etcd

# sudo journalctl -u etcd.service

export ETCDCTL_API=3
etcdctl --endpoints="192.168.56.11:2379,192.168.56.12:2379,192.168.56.13:2379" \
--cacert=/etc/kubernetes/pki/ca.crt \
--cert=/etc/kubernetes/pki/etcd.crt \
--key=/etc/kubernetes/pki/etcd.key \
endpoint status --write-out=table